from flask import Flask, request, jsonify
import bcrypt
import re
import logging

# Configure logging with more details
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# 模拟的用户数据库，存储已注册用户信息
users = []
app = Flask(__name__)

# 添加简单的CORS支持
@app.after_request
def after_request(response):
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
    response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
    return response

def is_valid_email(email):
    """验证邮箱格式是否正确"""
    pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    return re.match(pattern, email) is not None

def is_strong_password(password):
    """验证密码强度"""
    # 只验证密码长度至少6位
    return len(password) >= 6

@app.route('/register', methods=['POST'])
def register():
    try:
        # 记录收到的请求
        logger.debug(f"Received request headers: {dict(request.headers)}")
        logger.debug(f"Received request data: {request.get_data(as_text=True)}")

        # 从请求中获取用户信息
        if not request.is_json:
            logger.error("Request is not JSON")
            return jsonify({'message': '请求必须是JSON格式'}), 400

        data = request.get_json()
        if not data:
            logger.error("Empty JSON data")
            return jsonify({'message': '无效的请求数据'}), 400
            
        username = data.get('username')
        password = data.get('password')
        email = data.get('email')

        # 记录接收到的数据（注意不要记录密码）
        logger.debug(f"Received registration request for username: {username}, email: {email}")

        # 检查必要信息是否完整
        if not username or not password or not email:
            logger.error("Missing required fields")
            return jsonify({'message': '用户名、密码和邮箱是必需的'}), 400

        # 验证邮箱格式
        if not is_valid_email(email):
            logger.error(f"Invalid email format: {email}")
            return jsonify({'message': '无效的邮箱格式'}), 400

        # 验证密码强度
        if not is_strong_password(password):
            logger.error("Password does not meet strength requirements")
            return jsonify({'message': '密码必须至少6个字符'}), 400

        # 检查用户是否已经存在
        for user in users:
            if user.get('username') == username:
                logger.error(f"Username already exists: {username}")
                return jsonify({'message': '用户名已存在'}), 409
            if user.get('email') == email:
                logger.error(f"Email already registered: {email}")
                return jsonify({'message': '该邮箱已被注册'}), 409

        # 对密码进行加密
        hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())

        # 注册新用户
        new_user = {
            'username': username,
            'password': hashed_password.decode('utf-8'),
            'email': email
        }
        users.append(new_user)
        
        logger.info(f"New user registered successfully: {username}")
        return jsonify({'message': '注册成功'}), 201

    except Exception as e:
        logger.exception("Registration error occurred")  # This will log the full stack trace
        return jsonify({
            'message': '注册过程中发生错误',
            'error': str(e)  # 在开发环境中返回详细错误信息
        }), 500

if __name__ == '__main__':
    app.run(host='127.0.0.1', debug=True)